package com.fintech.pangu.oauth2.authentication.handler;

import com.alibaba.fastjson.JSON;
import com.fintech.pangu.commons.api.BaseResponse;
import com.fintech.pangu.commons.enums.BusinessEnum;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 表单登录认证失败处理器
 * 封装错误信息给前端
 */
public class FormAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String userName = request.getParameter("username");

        BaseResponse baseResponse;

        if (exception instanceof BadCredentialsException
                || exception instanceof UsernameNotFoundException){
            baseResponse = BaseResponse.failure(BusinessEnum.USERNAME_PASSWORD_ERROR);
        } else {
            baseResponse = BaseResponse.failure(BusinessEnum.USERINFO_AUTH_ERROR);
        }

        String error = JSON.toJSONString(baseResponse);
        error = URLEncoder.encode(error,"utf-8");

        request.setAttribute("userName",userName);
        request.setAttribute("msg",error);

        super.onAuthenticationFailure(request, response, exception);
    }
}
